/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tnmk.worktime.service.dao;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.tnmk.worktime.service.IoService;
import org.tnmk.worktime.service.dao.entry.SessionEntry;
import org.tnmk.worktime.service.dao.entry.SpendEntry;

/**
 *
 * @author tnmkhoi
 */
public class DailyRecordBuffer extends StorageBuffer {
  private static final DailyRecordBuffer instance = new DailyRecordBuffer();
  private static final Logger LOG = Logger.getLogger(DailyRecordBuffer.class);

  public static DailyRecordBuffer getInstance() {
    return instance;
  }
  private final IoService ioService;

  private DailyRecordBuffer() {
    ioService = IoService.getInstance();
    super.init();
  }

  @Override
  public void backupData() {
    this.ioService.backupData();
  }

  @Override
  public List<Class> getEntryClasses() {
    Class[] classes = {SessionEntry.class, SpendEntry.class};
    return Arrays.asList(classes);
  }

  @Override
  public boolean save() {
    try {
      Map<Class, DataTable> storage = super.getStorage();
      DataTable<SessionEntry> allSessions = storage.get(SessionEntry.class);//SessionEntries included SpendEntries
      ioService.saveHistoryToFile(allSessions.selectAll());
      return true;
    } catch (IOException ex) {
      LOG.error("Cannot save list all entries", ex);
      return false;
    }
  }

  @Override
  protected Map<Class, DataTable> initStorage() {
    Map<Class,DataTable> storage = new HashMap<>();
    List<SessionEntry> sessionsList = ioService.loadHistoryFromFile();
    DataTable<SessionEntry> sessions = new DataTable<>();
    storage.put(SessionEntry.class, sessions);
    DataTable<SpendEntry> spends = new DataTable<>();
    storage.put(SpendEntry.class, spends);
    sessions.addData(sessionsList);
    for (SessionEntry sessionEntry : sessionsList) {
      List<SpendEntry> spendList = sessionEntry.getMoneySpend().getItems();
      for (SpendEntry spendEntry : spendList) {
        spendEntry.setSessionId(sessionEntry.getId());
      }
      spends.addData(spendList);
    }
    return storage;
  }

}
